<script setup lang="ts">
import { useRouter } from 'vue-router';
import type { UserInfoData } from '@/types/my.ts';
import { uploadPost } from '@/services/index.ts';
import { informationGet, updateInformationPost } from '@/services/my.ts';

const formRef = ref();
const $router = useRouter();
const loading = ref(false);
const userInfoData: {
  form: UserInfoData;
} = reactive({
  form: {
    customerName: '',
    organizingInstitutionCode: '',
    legalPersonName: '',
    legalPersonIdNumber: '',
    legalPersonCardPictureObverse: [],
    legalPersonCardPictureReverse: [],
    legalPersonCardStartDate: '',
    legalPersonCardEndDate: '',
    contactMan: '',
    contactPhone: '',
    registeredAddress: '',
    taxpayerId: '',
    depositBank: '',
    bankAccount: '',
  },
});

const rules: any = reactive({
  customerName: [{ required: true, message: '请输入企业名称' }],
  organizingInstitutionCode: [{ required: false, message: '请输入组织机构代码' }],
  legalPersonName: [{ required: false, message: '请输入法人姓名' }],
  legalPersonIdNumber: [{ required: false, message: '请输入法人身份证号' }],
  legalPersonCardStartDate: [{ required: false, message: '请选择证件生效日期' }],
  legalPersonCardEndDate: [{ required: false, message: '请输入证件失效日期' }],
  legalPersonCardPictureObverse: [{ required: false, message: '请上传身份证正面' }],
  legalPersonCardPictureReverse: [{ required: false, message: '请上传身份证反面' }],
  contactMan: [{ required: true, message: '请输入联系人' }],
  contactPhone: [{ required: true, message: '请输入联系电话' }],
  registeredAddress: [{ required: true, message: '请输入注册地址' }],
  taxpayerId: [{ required: true, message: '请输入纳税人识别号' }],
  depositBank: [{ required: true, message: '请输入开户行' }],
  bankAccount: [{ required: true, message: '请输入银行账户' }],
});

const onSubmitClick = async () => {
  try {
    await formRef.value.validate();
    const params = JSON.parse(JSON.stringify(userInfoData.form));
    params.legalPersonCardPictureObverse = params.legalPersonCardPictureObverse[0]?.url;
    params.legalPersonCardPictureReverse = params.legalPersonCardPictureReverse[0]?.url;
    loading.value = true;
    const { err, message } = await updateInformationPost(params);
    if (err) {
      showToast(err);
    } else {
      showToast(message);
    }
    loading.value = false;
  } catch (errors) {
    console.log('表单验证失败', errors);
  }
};

// 上传图片处理
const afterRead = async (file: any, type: string) => {
  file.status = 'uploading';
  file.message = '上传中...';
  const formData = new FormData();
  formData.append('file', file.file);
  const { err, data } = await uploadPost(formData);
  if (err) {
    file.status = 'failed';
    file.message = '上传失败';
  } else {
    file.status = 'done';
    file.message = '上传成功';
  }
  userInfoData.form[type] = [{ url: data }];
};
const beforeRead = (file: any) => {
  const isJPG =
    file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/jpeg';
  const isLt1M = file.size / 1024 / 1024 < 10;
  if (!isJPG) {
    showToast('只能上传jpg/png/jpeg文件!');
  }
  if (!isLt1M) {
    showToast('上传图片大小不能超过 10MB!');
  }
  return isJPG && isLt1M;
};

// 时间选择器
const showPicker = ref(false);
const selectPick = ref('');
const onShowPickClick = (type: string) => {
  showPicker.value = true;
  selectPick.value = type;
};
const onConfirm = ({ selectedValues }: { selectedValues: string[] }) => {
  userInfoData.form[selectPick.value] = selectedValues.join('/');
  showPicker.value = false;
};

const loadData = async () => {
  const { err, data } = await informationGet();
  if (err) {
    showToast(err);
    return;
  }
  // 这个字段如果不传就代表着证件未修改 需要讲所有的数据全部传给后端 并且删除证件信息字段
  delete data.customerQualificationList;
  userInfoData.form = {
    ...data,
    legalPersonCardPictureReverse: data.legalPersonCardPictureReverse
      ? [{ url: data.legalPersonCardPictureReverse }]
      : [],
    legalPersonCardPictureObverse: data.legalPersonCardPictureObverse
      ? [{ url: data.legalPersonCardPictureObverse }]
      : [],
  };
};
onMounted(() => {
  loadData();
});
</script>

<template>
  <div class="login-container">
    <van-form
      :model="userInfoData.form"
      required="auto"
      :rules="rules"
      ref="formRef"
      label-width="7em"
    >
      <div class="inputSpace">
        <van-field
          label="企业名称"
          placeholder="请输入企业名称"
          :rules="rules.customerName"
          v-model="userInfoData.form.customerName"
          name="customerName"
        />
        <van-field
          label="组织机构代码"
          :rules="rules.organizingInstitutionCode"
          v-model="userInfoData.form.organizingInstitutionCode"
          name="organizingInstitutionCode"
          placeholder="请输入组织机构代码"
        />
      </div>
      <div class="inputSpace">
        <van-field
          label="法人姓名"
          :rules="rules.legalPersonName"
          name="legalPersonName"
          v-model="userInfoData.form.legalPersonName"
          placeholder="请输入法人姓名"
        />
        <van-field
          label="身份证号"
          :rules="rules.legalPersonIdNumber"
          v-model="userInfoData.form.legalPersonIdNumber"
          name="legalPersonIdNumber"
          placeholder="请输入法人身份证号"
        />
        <van-field
          label="身份证正面"
          :rules="rules.legalPersonCardPictureObverse"
          name="legalPersonCardPictureObverse"
          placeholder="请上传身份证正面"
        >
          <template #input>
            <van-uploader
              v-model="userInfoData.form.legalPersonCardPictureObverse"
              :before-read="beforeRead"
              :after-read="(file: any) => afterRead(file, 'legalPersonCardPictureObverse')"
              :max-count="1"
            >
              <template #default>
                <div class="upload-style">
                  <svg-icon icon-class="uploader" size="1.4em" />
                </div>
              </template>
            </van-uploader>
          </template>
        </van-field>
        <van-field
          label="身份证反面"
          :rules="rules.legalPersonCardPictureReverse"
          name="legalPersonCardPictureReverse"
          placeholder="请上传身份证正面"
        >
          <template #input>
            <van-uploader
              v-model="userInfoData.form.legalPersonCardPictureReverse"
              :before-read="beforeRead"
              :after-read="(file: any) => afterRead(file, 'legalPersonCardPictureReverse')"
              :max-count="1"
            >
              <template #default>
                <div class="upload-style">
                  <svg-icon icon-class="uploader" size="1.4em" />
                </div>
              </template>
            </van-uploader>
          </template>
        </van-field>
        <van-field
          label="证件生效日期"
          :rules="rules.legalPersonCardStartDate"
          name="legalPersonCardStartDate"
          v-model="userInfoData.form.legalPersonCardStartDate"
          @click="onShowPickClick('legalPersonCardStartDate')"
          placeholder="点击选择证件生效日期"
        />
        <van-field
          label="证件失效日期"
          :rules="rules.legalPersonCardEndDate"
          v-model="userInfoData.form.legalPersonCardEndDate"
          @click="onShowPickClick('legalPersonCardEndDate')"
          name="legalPersonCardEndDate"
          placeholder="请输入组织机构代码"
        />
      </div>
      <div class="inputSpace">
        <van-field
          label="联系人"
          :rules="rules.contactMan"
          v-model="userInfoData.form.contactMan"
          name="contactMan"
          placeholder="请输入联系人"
        />
        <van-field
          label="联系电话"
          :rules="rules.contactPhone"
          v-model="userInfoData.form.contactPhone"
          name="contactPhone"
          placeholder="请输入联系电话"
        />
        <van-field
          label="注册地址"
          :rules="rules.registeredAddress"
          v-model="userInfoData.form.registeredAddress"
          name="registeredAddress"
          placeholder="请输入注册地址"
        />
        <van-field
          label="纳税识别号"
          :rules="rules.taxpayerId"
          v-model="userInfoData.form.taxpayerId"
          name="taxpayerId"
          placeholder="请输入纳税识别号"
        />
        <van-field
          label="开户行"
          :rules="rules.depositBank"
          v-model="userInfoData.form.depositBank"
          name="depositBank"
          placeholder="请输入开户行"
        />
        <van-field
          label="银行账号"
          :rules="rules.bankAccount"
          v-model="userInfoData.form.bankAccount"
          name="bankAccount"
          placeholder="请输入银行账号"
        />
      </div>
      <div class="user-bottom">
        <van-button @click="onSubmitClick" :loading="loading" color="#E89000" round block>
          保存并提交审核
        </van-button>
        <van-button @click="$router.go(-1)" color="#E89000" plain round block> 返回</van-button>
      </div>
    </van-form>
    <van-popup v-model:show="showPicker" destroy-on-close position="bottom">
      <van-date-picker @confirm="onConfirm" @cancel="showPicker = false" />
    </van-popup>
  </div>
</template>

<style lang="scss" scoped>
.login-container {
  width: 100%;
  display: flex;
  justify-content: center;
  flex-direction: column;
  background: #f6f6f6;

  .inputSpace {
    margin-bottom: 4px;
  }

  .user-bottom {
    width: 100%;
    padding: 0 16px;
    margin: 30px 0;

    .van-button {
      height: 40px;
      margin: 8px 0;
    }
  }

  .register_footer {
    background: white;
    padding: 16px 16px 25px 16px;

    .checkbox {
      display: flex;
      align-items: flex-start;
      font-size: 12px;

      .van-checkbox {
        width: 30px;
        margin-top: 3px;
      }

      .checkText {
        color: #aaaaaa;
      }
    }

    .footer_message {
      width: 100%;
      display: flex;
      justify-content: center;
      font-size: 13px;
      color: #00ba9f;
    }
  }
}
</style>
